
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>WebGL Visualization</title>
    </head>
	
    <script language="javascript" type="text/javascript" src="shaderProgram.js"></script>
    <script language="javascript" type="text/javascript" src="testcube.js"></script>
    <script language="javascript" type="text/javascript" src="sylvester.js"></script>
    <script language="javascript" type="text/javascript" src="glUtils.js"></script>
    <script language="javascript" type="text/javascript" src="matrixstack.js"></script>
	<script language="javascript" type="text/javascript" src="webgl10errors.js"></script>
	<script language="javascript" type="text/javascript" src="IndexedModel.js"></script>
	<script language="javascript" type="text/javascript" src="dxf/dxfparser.js"></script>
	<script language="javascript" type="text/javascript" src="dxf/dxfnode.js"></script>
	<script language="javascript" type="text/javascript" src="wireframe.js"></script>
	<script language="javascript" type="text/javascript" src="Camera.js"></script>
	<script src="jquery.js"></script>
    <script language="javascript" type="text/javascript">
        
        var horizAspect = 480.0 / 640.0;
        
        var myCube, myProgram1, myProgram2;
        var yRotation = 0.0;
		var xRotation = 0.0;
		var startDragX = 0.0;
		var startDragY = 0.0;

		var wireframe = null;

		var lastFrameTime;
		
		var isMouseButtonPressed;
		var oldXRotation, oldYRotation;
		
		var flatFragText = null;
		var flatVertText = null;
		var flatProgram = null;

		var lightDir = new Float32Array([0, Math.sqrt(2)/2, Math.sqrt(2)/2]);

		var camera = null;
		var oldPosition = null;
		
		var mvMatrixStack = null;
		var projMatrixStack = null;

		var canvas;
		var dragTranslate = null;

		function requestFile(fileName, callback) {
			var httpRequest;
			
			var file = null;
			
			if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	   			httpRequest = new XMLHttpRequest();
			} else if (window.ActiveXObject) { // IE
	   		 	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			httpRequest.onreadystatechange = function() {
				if (httpRequest.readyState === 4) {
					file = httpRequest.responseText;
					callback(file);
				}
				else {
					;
				}
			};
			httpRequest.open('GET', fileName, true);
			httpRequest.send(null);
						
		}
		        
		function getObjectCoordinates(x, y) {
			
            offset = $(canvas).offset();
            
            // get the viewport
            var viewPort = gl.getParameter(gl.VIEWPORT);
            var location = camera.unProject(x - offset.left, 768 - (y - offset.top), 1, camera.getModelViewMatrix(), pMatrixStack.matrix, viewPort);
            
            var cpos4 = $V([camera.position.e(1), camera.position.e(2), camera.position.e(3), 1]);
            var raydirection = $V(location).subtract(cpos4);
            var rayorigin = cpos4;
            
            var n = $V([0, 0, 1, 0]);
            
            var t = -rayorigin.dot(n) / raydirection.dot(n);
            
            var objectCoords = rayorigin.add(raydirection.multiply(t));
            
			return objectCoords;
			
		}
				
		function mouseDown(event) {
			isMouseButtonPressed = true;
			var coords = getObjectCoordinates(event.clientX, event.clientY);
			startDragX = coords.e(1);
			startDragY = coords.e(2);
			oldPosition = camera.position;
			
		}
		
		function mouseUp(event) {
			isMouseButtonPressed = false;
						
			var coords = getObjectCoordinates(event.clientX, event.clientY);
			
			if (oldPosition) {
				camera.position = $V([oldPosition.e(1) - (coords.e(1) - startDragX), oldPosition.e(2) - (coords.e(2) - startDragY), oldPosition.e(3), ]);
			}
			
			dragTranslate = $V([0.0, 0.0, 0.0]);

			
		}
		
		function mouseMoved(event) {
			if ( isMouseButtonPressed ) {
				
				var coords = getObjectCoordinates(event.clientX, event.clientY);
		
				dragTranslate = $V([
					 ( coords.e(1) - startDragX ),
					 ( coords.e(2) - startDragY ),
					 0,
				]);
				
			}
		}
		
		function outerDrawScene() {
			var currentTime = (new Date).getTime();
			var delta = 0;
			if (lastFrameTime) {
				delta = currentTime - lastFrameTime;
				if ( delta > 100 ) {
					delta = 100;
				}
				else if ( delta < 0 ) {
					delta = 0;
				}
			}
			drawScene(delta / 1000);
			lastFrameTime = currentTime;
		}
		
        function drawScene(delta){
			
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
                        
		
			var cameraMat = camera.getModelViewMatrix();
			
			mvMatrixStack.loadMatrix(cameraMat);
			pMatrixStack.loadMatrix(makePerspective(45, 640.0 / 480.0, 0.1, 20000.0));
            
			if ( dragTranslate ) {
				mvMatrixStack.translate(dragTranslate.elements);
			}
			
            if (wireframe != null) {
				
                flatProgram.useProgram();
				rb_check_error("use program");

                mvMatrixStack.setMatrixUniforms(flatProgram.program, "uMVMatrix");
				pMatrixStack.setMatrixUniforms(flatProgram.program, "uPMatrix");
				rb_check_error("set matrix");
				
                wireframe.draw(	flatProgram.locationForAttribute("position"), 
								flatProgram.locationForAttribute("color_in"));
											
				rb_check_error("draw");

            }

			rb_check_error("end of frame");
        }
                
        function initTexture(imageSource){
            console.log("init texture");
            var cubeTexture = gl.createTexture();
            var cubeImage = new Image();
            cubeImage.onload = function(){
                handleTextureLoaded(cubeImage, cubeTexture);
            }
            cubeImage.src = imageSource;
            
            return cubeTexture;
        }
        
        function handleTextureLoaded(image, texture){
            console.log("handleTextureLoaded, image = " + image);
            gl.bindTexture(gl.TEXTURE_2D, texture);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
            gl.generateMipmap(gl.TEXTURE_2D);
            gl.bindTexture(gl.TEXTURE_2D, null);
        }
				
        function start(){
            
			canvas = document.getElementById("glcanvas");
			document.onselectstart = function() {return false;};
			
            initWebGL(canvas);
			
            if (gl) {
				
                gl.clearColor(0.95, 0.95, 0.95, 1.0);
                gl.clearDepth(1.0);
                gl.enable(gl.DEPTH_TEST);
                gl.depthFunc(gl.LEQUAL);
                gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
				// gl.enable(gl.BLEND);
				gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
				
				canvas.onmousemove = mouseMoved;
				canvas.onmousedown = mouseDown;
				canvas.onmouseup   = mouseUp;
				canvas.onmouseout  = mouseUp;
                
				mvMatrixStack = new matrixstack();
				pMatrixStack = new matrixstack();

				camera = new Camera();
				camera.position = $V([0.0, 0.0, 500.0]);
				camera.viewDirection = $V([0, 2, -1]);

                requestFile("643-r12.DXF", function(file){
					console.log("about to parse stuff :(")
                    var parser = new DXFParser(file);
					
					wireframe = new Wireframe();
					wireframe.build(parser);
					
					rb_check_error("end building wireframe");

                });

                
                var checkShader = function(){
                    console.log("checkShader")
					if ( flatVertText && flatFragText && !flatProgram ) {
						flatProgram = new shaderProgram(flatVertText, flatFragText);
						flatProgram.linkProgram();
					}
                }
				       
				requestFile("shaders/flat.fsh", function(file){
                    flatFragText = file;
                    checkShader();
                });
                requestFile("shaders/flat.vsh", function(file){
                    flatVertText = file;
                    checkShader();
                });
         				
                setInterval(outerDrawScene, 15);
                
                console.log("done loading");

		    }
        }
        
		function selectModel(object) {
			mode = object.value;
		}
		
        function initWebGL(){
            gl = null;
            try {
                gl = canvas.getContext("experimental-webgl");
            } 
            catch (e) {
            }
            if (!gl) {
                alert("Unable to initialize WebGL.  Your browser may not support it.");
            }
        }
		
    </script>
    <body onload="start()">
    	<div style="margin-left: auto; margin-right: auto; width: 800px">
     	 <!--  <h1 style="text-align: center; color: #aaaaaa">WebGL Model Viewer</h1> -->
        <canvas id="glcanvas" width="800" height="768" style="border: 1px dashed black;">
            Your browser doesn't appear to support the HTML5 
            <code>
                &lt;canvas&gt;
            </code>
            element.
        </canvas>
		
		<div style="border: 1px dashed black; padding: 10px; margin: 0; background-color: #ffffdd">
		<p>Drag the mouse to pan over the model</p>
		
		</div>
		</div>
    </body>
</html>
